using System.Collections.Generic;
using Entity;
using Utils;

namespace Mapper
{
    public class PackageMapper
    {
        private const string TABLE_NAME = "package";

        public  PackageMapper()
        {
            MySQLUtil.CreateConnection();
        }
        
        public void CloseConnection()
        {
            MySQLUtil.Close();
        }

        public List<Package> ListAllPackages()
        {
            return MySQLUtil.SelectData<Package>(TABLE_NAME, "*", null);
        }

        public List<Package> ListPackagesPage(int current, int pageSize)
        {
            int start = (current - 1) * pageSize;
            int end = current * pageSize;
            return MySQLUtil.SelectData<Package>(TABLE_NAME, "*", "", start, end);
        }

        public List<UserPackageVO> ListPackagesByUserId(long userId)
        {
            return MySQLUtil.SelectData<UserPackageVO>($"select package.* , rel.packageCount from package_user_rel rel , package where rel.packageId = package.id and rel.userId = {userId}");
        }
        
        public List<UserPackageVO> GetPackageByUserIdAndPackageId(long userId , int packageId)
        {
            return MySQLUtil.SelectData<UserPackageVO>($"select package.* , rel.packageCount from package_user_rel rel , package where rel.packageId = package.id and rel.userId = {userId} and rel.packageId = {packageId}");
        }

        public void AddUserPackageRelData(int packageId, long userId , int packageCount)
        {
            MySQLUtil.AddData($"insert into package_user_rel (packageId , userId , packageCount) values ({packageId}, {userId}, {packageCount})");
        }
        
        public void UpdateUserPackageRelDataByPackageIdAndUserId(int packageId, long userId , int packageCount)
        {
            MySQLUtil.AddData($"update package_user_rel set packageCount = {packageCount} where packageId = {packageId} and userId = {userId}");
        }

        public void DeleteUserPackageRelDataByPackageIdAndUserId(int packageId, long userId)
        {
            MySQLUtil.UpdateData($"delete from package_user_rel where packageId = {packageId} and userId = {userId}");
        }
    }
}